import { xhrGet, xhrPostJson } from "@/services";
import { isObject } from "@umijs/deps/compiled/lodash";
import { Input } from "antd";
import { useEffect, useState } from "react";

export interface DisplayInputProps {
    api: any;
    value: any;
    editable: boolean;
    keyName: string;
}

const DisplayInput: React.FC<DisplayInputProps> = (props) => {
    const { value, api, editable, keyName = 'name', ...restProps } = props;
    const [displayValue, setDislayValue] = useState<string>(value);
    const getName = async () => {
        const { method, url, params } = api;
        const res: any = method?.toUpperCase() === 'POST' ? await xhrPostJson(url, {
            ...params,
            code: value
        }) : await xhrGet(url, {
            ...params,
            code: value
        });
        if (res.success) {
            setDislayValue(typeof(res.result)=='string' ?  res.result: (keyName? (res?.result?.[keyName]):''))
        }
    }
    useEffect(() => {
        if (value) {
            getName()
        }
    }, [JSON.stringify(api)])
    useEffect(() => {
        if (value) {
            getName()
        }
    }, [JSON.stringify(value)])
    console.log('value', value);
    return <>
        {
            editable ? <Input {...restProps} value={displayValue} /> : displayValue
        }
    </>;
}

export default DisplayInput;